#region Imported Namespaces
using System;
using Workflow.NET;
using WorkFlowEngine = Workflow.NET.Engine;
using WorkFlowAction = Workflow.NET.ActionHandler;
using WorFlowInterface = Workflow.NET.Engine.Interfaces;
using PHSRAG.Insight21.Policy;
using System.Collections;
using InsightHumans = PHSRAG.Insight21.Humans;
using System.Threading;
using PHSRAG.Utility;
using System.Data.SqlClient;
using System.Data;
using System.Web;
#endregion 

namespace PHSRAG.Insight21.InsightWorkFlow
{
    public class ResetWorkflowVariables : Workflow.NET.Engine.Interfaces.IActionRun
    {
        /// Default constructor
        public ResetWorkflowVariables() {}

        public WorFlowInterface.ActionResult Run(int executionId, int executionDetailsId, WorkFlowEngine.Context currentContext, Action currentAction, string inlinkOutput, bool retry, out string output)
        {
            output = null;
            Log logger = currentContext.log;
            HumansWorkFlow humansWF = new HumansWorkFlow(new NullCachePolicy());

            try
            {                
                object insightApplicationName = currentContext.Contents["insightApplicationName"];
                HumansWorkFlow.InsightApplicationName = (null == insightApplicationName) ? string.Empty : ((Content)insightApplicationName).Value.ToString();
                Thread.SetData(Thread.GetNamedDataSlot("Connections"), HumansWorkFlow.Connections);
                int PIOrganizationId = 0;
                string PIOrganizationName = string.Empty;
                if (currentContext.Variables["protocolNumber"] != null)
                    currentContext.Variables["protocolNumber"].Value = String.Empty;
                currentContext.Variables["submissionType"].Value = String.Empty;
                currentContext.Variables["comments"].Value = String.Empty;

                SqlDataReader reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), "GetRunEnvironment");

                if (executionId != 0)
                {
                    currentContext.Variables["executionId"].Value = executionId;

                    reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), 
                                                    "GetExecutionDetails", 
                                                    DataAccess.BuildSqlParameterArray("@executionId", SqlDbType.Int, executionId));

                    if (reader.Read())
                    {                        
                        PIOrganizationId = Int32.Parse(reader["PIOrgId"].ToString());
                        PIOrganizationName = reader["PIOrgName"].ToString();
                        if (currentContext.Variables["protocolNumber"] != null)
                            currentContext.Variables["protocolNumber"].Value = (reader["ProtocolNumber"].ToString() == String.Empty) ? "NA" : reader["ProtocolNumber"].ToString();
                        currentContext.Variables["submissionType"].Value = reader["SubmissionType"].ToString();                        
                    }

                    reader.Close();
                    reader.Dispose();
                }

                if (!PIOrganizationName.ToString().Contains("SRH") && !PIOrganizationName.ToString().Contains("IHP") || PIOrganizationName == String.Empty)
                    PIOrganizationId = 1;

                if (executionId != 0)
                {
                    reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), 
                                                        "GetWorkflowDetailedComments",
                                                        DataAccess.BuildSqlParameterArray("@executionId", SqlDbType.Int, executionId));
                    if (reader.Read())
                    {
                        currentContext.Variables["comments"].Value = reader["comments"].ToString();
                    }

                    reader.Close();
                    reader.Dispose();
                }

                //don't want to reset Anci Board Users for resubmission.
                ArrayList varAnciArrayList = new ArrayList();
                if (!PIOrganizationName.ToString().Contains("SRH"))
                {
                    varAnciArrayList = humansWF.GetAncillaryBoardUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));
                    currentContext.Variables["anciBoardUser"].Value = varAnciArrayList;
                }

                if (varAnciArrayList != null)
                    humansWF.SetContextVariables("anciBoardUser", varAnciArrayList, Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Set the flag for board users. If this flag is 1 then Board approval process will be called in Workflow.
                if ((varAnciArrayList != null) && (varAnciArrayList.Count > 0))
                    currentContext.Variables["boardUsersExist"].Value = 1;
                else
                    currentContext.Variables["boardUsersExist"].Value = 0;
            
                currentContext.SaveVariables();
                output = "Success";
            }
            catch (Exception ex)
            {
                logger.LogMessage(ReasonConst.Error, "Unable to resetset workflow variables in ResetWorkFlowVariables.Run() " + ex.InnerException.ToString());
                output = "Failure";
            }
            finally
            {
                humansWF.Dispose();
            }
            return WorFlowInterface.ActionResult.Completed;
        }

        public virtual Workflow.NET.Interfaces.IActivityWebUIHandler GetActivityWebUIHandler()
        {
            return null;
        } 
    }
}